package com.lry.basic.metrics;

import com.lry.basic.metrics.spi.LoadLevel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

@LoadLevel(name = "compact", order = 1)
public class CompactRegistry  implements  Registry{

    private static final Map<UUID,Meter> METERS = new ConcurrentHashMap<>();

    @Override
    public <T extends Number> Gauge<T> getGauge(Id id, Supplier<T> supplier) {
       return (Gauge<T>) CompactRegistry.METERS.computeIfAbsent(id.getId(), key-> new CompactGauge<>(id,supplier));
    }

    @Override
    public Counter getCounter(Id id) {
        return (Counter) CompactRegistry.METERS.computeIfAbsent(id.getId(), key -> new CompactCounter(id));
    }

    @Override
    public Summary getSummary(Id id) {
        return (Summary)CompactRegistry.METERS.computeIfAbsent(id.getId(), key -> new CompactSummary(id));
    }

    @Override
    public Timer getTimer(Id id) {
        return (Timer)CompactRegistry.METERS.computeIfAbsent(id.getId(), key -> new CompactTimer(id));
    }

    @Override
    public Iterable<Measurement> measure() {
        List<Measurement> measurements = new ArrayList<>();
        if (CompactRegistry.METERS.size() == 0) {
            return measurements;
        }
        CompactRegistry.METERS.values().iterator().forEachRemaining(
                meter -> meter.measure().forEach(measurements::add)
        );
        return measurements;
    }
}
